package com.lebang.controller.api.bus;

import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.Sessionid;
import com.lebang.common.MemberLock;
import com.lebang.common.Require;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.feign.AppDictFeign;
import com.lebang.feign.SmallAmountWithdrawalFeign;
import com.lebang.model.*;
import com.lebang.model.back.Result;
import com.lebang.model.enums.ResultVo;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.BusWithdrawDepositService;
import com.lebang.service.MemberWalletService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.buss.MemberTradeService;
import com.lebang.service.buss.WalletService;
import com.lebang.service.sys.MemberCashWithdrawalService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 公交小额提现
 *
 * @Author: ljx
 * @Date: 2020/12/1
 */
@Api(tags = "公交小额提现")
@RestController
@RequestMapping("/bus/withdrawdeposit")
public class BusWithdrawDepositApi {
    @Autowired
    private SmallAmountWithdrawalFeign feign;
    @Autowired
    private MemberService memberService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private MemberCashWithdrawalService memberCashWithdrawalService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private MemberTradeService memberTradeService;
    @Autowired
    private BusWithdrawDepositService busWithdrawDepositService;
    @Autowired
    private AppDictFeign appDictFeign;

    /**
     * 是否存在记录
     *
     * @param request
     * @return
     */
    @Require
    @ApiOperation("是否存在记录")
    @PostMapping("/isexists")
    public JsonData isExists(HttpServletRequest request) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        LbbMember member = memberService.getMemberByMemberId(userInfo.getMemberId());
        if (TextUtil.isEmpty(member.getWxOpenid())) {
            return Callback.fail("201", "记录已存在");
        }
        return feign.isExists(userInfo, member.getWxOpenid());
    }

    /**
     * 领取0.3元
     *
     * @param request
     * @return
     */
    @Require
    @Sessionid
    @Transactional(rollbackFor = Exception.class)
    @MemberLock
    @ApiOperation("领取0.3元")
    @PostMapping("/addrecord")
    public JsonData addRecord(HttpServletRequest request) {
        RequestHeaders headers = new RequestHeaders(request);
        RequestUserInfo userInfo = new RequestUserInfo(request);
        LbbMember member = memberService.getMemberByMemberId(userInfo.getMemberId());
        if (TextUtil.isEmpty(member.getWxOpenid())) {
            return Callback.fail("201", "领取失败");
        }
        JsonData jsonData = feign.addrecord(userInfo, member.getWxOpenid());
        if (jsonData.isSuccess()) {
            int money = Integer.parseInt(JSONObject.toJSONString(jsonData.getData()));
            memberTradeService.addMoney(headers.getUserid(), money,
                    "新人专享", "领取成功", "", headers, "", new MoneyCategory(Whether.YES, TaskCategory.ROUSE_DAY));
            return Callback.success("200", "领取成功");
        }
        return Callback.fail("202", "领取失败");
    }

    /**
     * 获取配置
     *
     * @param request
     * @return
     */
    @Require
    @ApiOperation("获取配置")
    @PostMapping("/getconfig")
    public JsonData getConfig(HttpServletRequest request) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        LbbMember member = memberService.getMemberByMemberId(userInfo.getMemberId());
        return feign.getConfig(userInfo, member.getWxOpenid());
    }


    /**
     * 提现
     *
     * @param request
     * @return
     */
    @Require
    @Sessionid
    @Transactional(rollbackFor = Exception.class)
    @MemberLock
    @PostMapping("/push")
    @ApiOperation("提现")
    public JsonData push(HttpServletRequest request, Integer type, Integer configId) {
        RequestHeaders headers = new RequestHeaders(request);
        RequestUserInfo userInfo = new RequestUserInfo(request);
        if (type != 2) {
            return Callback.fail("201", "请选择微信提现!");
        }
        if (TextUtil.isEmpty(configId)) {
            return Callback.fail("202", "配置不存在");
        }
        try {
            LbbMember member = memberService.getMemberByMemberId(userInfo.getMemberId());
            JsonData dataValue = appDictFeign.get("quick_withdraw_is_need_phone", userInfo.getAppId());
            if (dataValue.isSuccess()){
                try {
                    AppDictModel appDict = JSONObject.parseObject(JSONObject.toJSONString(dataValue.getData()), AppDictModel.class);
                    int value = Integer.parseInt(appDict.getKeyvalue());
                    // 打开开关
                    if (value == 1){
                        if (member.getPhone() == null) {
                            return Callback.fail("208", "提现失败,未绑定手机号!");
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                return Callback.fail("202", "字典不存在");
            }
            if (member.getWxStatus().equals(0)) {
                return Callback.fail("204", "转账失败,用户微信未绑定!!");
            }
            if (memberCashWithdrawalService.allow(headers.getUserid())) {
                return Callback.fail("205", "您还有一笔提现申请未处理，请等待!");
            }
            long money = memberWalletService.getMoneyByMemberId(headers.getUserid());
            Integer amounts = walletService.getAllows(headers.getUserid(), headers.getAppid());
            JsonData data = feign.amount(userInfo, configId,member.getWxOpenid(),member.getPhone());
            if (!data.isSuccess()){
                return Callback.fail("202", "记录不存在");
            }
            int amount = Integer.parseInt(JSONObject.toJSONString(data.getData()));
            if (amount > amounts || amount > money) {
                return Callback.fail("206", "您的可提现金额不足!");
            }
            JsonData jsonData = feign.pull(userInfo, configId, member.getWxOpenid(), member.getPhone(),member.getNickname(),headers.getIpAddr());
            if (jsonData.isSuccess()) {
                WithdrawalModel record = JSONObject.parseObject(JSONObject.toJSONString(jsonData.getData()), WithdrawalModel.class);
                busWithdrawDepositService.creatFastWishCash(member,type,amount,headers,record.getTradeNo());
                //mysql持久化
                memberWalletService.outLayMoney(record.getMemberId(), record.getMoney());
            } else {
                return Callback.fail("207", "提现失败,请联系在线客服处理!" + jsonData.getData(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Callback.fail("fail", "提现失败,请联系在线客服处理!");
        }
        return Callback.success("success", "领取成功");
    }

    /**
     * 是否提现
     */
    @Require
    @PostMapping("/getstatus")
    @ApiOperation("是否提现")
    public JsonData getStatus(HttpServletRequest request) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        LbbMember member = memberService.getMemberByMemberId(userInfo.getMemberId());
        JsonData jsonData = feign.isPull(userInfo, member.getWxOpenid());
        if (jsonData.isSuccess()) {
            return Callback.success("200", "未提现");
        }
        return Callback.fail("201", "已提现");
    }

    /**
     * 记录填充
     */
    @Require
    @PostMapping("/update")
    @ApiOperation("记录填充")
    public JsonData update(HttpServletRequest request, @RequestParam("configId") Integer configId) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        JsonData dataValue = appDictFeign.get("quick_withdraw_is_need_phone", userInfo.getAppId());
        if (dataValue.isSuccess()){
            try {
                AppDictModel appDict = JSONObject.parseObject(JSONObject.toJSONString(dataValue.getData()), AppDictModel.class);
                int value = Integer.parseInt(appDict.getKeyvalue());
                // 打开开关
                if (value == 1){
                    System.out.println("开启开关");
                    LbbMember member = memberService.getMemberByMemberId(userInfo.getMemberId());
                    if (TextUtil.isEmpty(member.getPhone())) {
                        return Callback.fail("202", "提现失败,未绑定手机号!");
                    }
                    return feign.update(userInfo, member.getWxOpenid(), member.getPhone(), configId);
                }else {
                    System.out.println("关闭开关");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return Callback.success("200","返回成功");
        }else {
            return Callback.fail("202", "字典不存在");
        }
    }

}
